let router = require('koa-router')();
let Comment = require('../models/comment.js');
let User = require('../models/user.js');
router.prefix('/comment');
/**
 * 评论
 */
router.post('/add', async (ctx, next) => {
  try {
    let { star, title, content, id, name } = ctx.request.body;
    await Comment.create({ doubanId: id, from: ctx.userId, star, content, title, name });
    ctx.success({msg: `comment success`});
  } catch (err) {
    throw err;
  }
});
/**
 * 获取评论列表
 */
router.get('/lists', async (ctx, next) => {
  try {
    let { id } = ctx.query;
    let comments = await Comment.find({doubanId: id});
    for (let i = 0; i < comments.length; i++) {
      let u = await User.findOne({userId: comments[i].from});
      comments[i]._doc.username = u._doc.username || '';
      comments[i]._doc.avatar = u._doc.avatar || '';
    }
    ctx.success(comments);
  } catch (err) {
    throw err;
  }
});

/**
 *给评论点赞或吐槽
 */
router.post('/zan', async (ctx, next) => {
  try {
    let { id = '', flag = 1 } = ctx.request.body;
    if (!id) {
      throw new Error('缺少参数');
    }
    let comment = await Comment.findOne({_id: id});
    let users = comment.zan.users.concat(comment.noZan.users);
    if (!users.includes(ctx.userId + '')) {
      if (+flag === 1) {
        comment.zan.count++;
        comment.zan.users.push(ctx.userId);
      } else if (+flag === 2) {
        comment.noZan.count++;
        comment.noZan.users.push(ctx.userId);
      }
    }
    await comment.save();
    ctx.success({msg: 'comment success'});
  } catch (err) {
    throw err;
  }
});

/**
 * 获取我的评论
 */
router.get('/getMyComments', async (ctx, next) => {
  try {
    let comments = await Comment.find({from: ctx.userId}).select('doubanId');
    let arrs = comments.map(item => item.doubanId);
    ctx.success(arrs);
  } catch (err) {
    throw err;
  }
});
module.exports = router
;
